import utils from './delivery-data.js'
import tool from './deliveryTool.js'
import refeFreightTool from "./refeFreightTool.js";
import sysFreightTool from "./sysFreightTool.js";
import {
	phone_rule,
	phone_check,
	validate_amount,
	check_amount,
} from "@/common/rules.js";
export default {
	components: {

	},
	data() {
		return {
			goodsPackList: utils.getPackFromData(),
			inputData: {
			waybill_sn: '', //运单号
			goodsn: '', //货号

			to_address: "",
			to_province_id: "",
			to_city_id: "",
			to_county_id: "",
			to_province_name: "",
			to_city_name: "",
			to_county_nane: "",
			system_line_price: "0",
			system_markup_price: "0",

			line_id: '',
			company_id: '', //物流公司id
			company_name: '', //物流公司
			memberno: "",

			deliver_point: '', //发货网站id
			deliver_point_name: '', //发货网站
			arrival_point: '', //收货网站id
			arrival_point_name: '', //收货网站

			send_username: '',
			send_mobile: '',
			send_city: '',
			send_address: '',
			send_province_id: '',
			send_city_id: '',
			send_area_id: '',
			send_card: "",
			send_accountname: "", //户号
			send_account: "", //银行卡号
			send_bankname: "", //银行名称

			take_addressid: '0',
			take_username: '',
			take_mobile: '',
			take_city: '',
			take_address: '',
			take_province_id: '',
			take_city_id: '',
			take_area_id: '',

			goods: [{
				goods_name: '',
				goods_pack: '',
				goods_nums: "1",
				total_weight: "1",
				total_volume: "1",
			}],

			order_amount: '', //运费
			pickup_fee: '0', //接货费
			delivery_fee: '0', //送货费
			information_fee: '0', //信息费
			transit_fee: '0', //中转费
			insurance_fee: '0',
			transit_destination: '', //中转城市
			advance_amount: '0', //代收款
			open_order_fee: "0",
			operating_fee: "0",
			platform_amount: "0",
			
			order_amount_pay: "20",
			order_amount_pay_name:'提付',
			pickup_fee_pay: "20",
			delivery_fee_pay: "20",
			information_fee_pay: "20",
			transit_fee_pay: "20",
			go_upstairs_fee_pay: "20",
			all_order_amount: "0",
			carry_order_amount: "0",
			now_order_amount: "0",
			pay_from: '20', //支付方式
			delivery_type: '1', //配送方式
			delivery_type_name:'自提',
			is_receipt: '1', //回单收条:1=无需,2=回单
			receipt_type: "", //回单类型
			receipt_type_name:'',
			receipt_num: "",
			is_unusual: '1', //是否是异形件:1=否,2=是
			is_control: "1",//是否控货1否2是
			is_urgency: "1",//是否是急件1否2是
			remark: "",
			order_type: 10, //订单类型:10=线上,20=线下
			is_transit: "",
			pay_source: '10', //支付来源：miniapp=小程序，app=APP
			reach_type: '', //交货方式
		},
			
			deliveryType: utils.getDeliveryTypeData(), //配送方式
			receiptList: utils.getReceiptTypeData(), //回单收条
			payFromList: utils.getPayFromData(), //支付类型
			memberinfo:{},
			searchPriceData: {},
			toData: {},
			companyList: [],
			startSiteList: [],
			endSiteList: [],
			address_type_city: 0,

			indicatorStyle: `height: 50px;`,
			selectList: [0, 0, 0],

			provinceList: [],
			cityList: [],
			areaList: [],
			siteInfo: {},
			provinceInfo: '',
			goodsArr: [],
			page_type: '',

			servicePriceData: {
				caozuo_weight: "0",
				caozuo_volume: "0",
				kaipiao_fee: "0.00",
				caozuo_fee0: "0.00",
				caozuo_fee1: "0.00",
				caozuo_fee2: "0.00"
			},
			searchPriceData: {
				kaipiao_fee: '',
				caozuo_weight: '',
				to_province: '',
				to_city: '',
				to_county: '',
				markup_type: 1,
				markup_number: '0.0',
				billing_model: 1,
				weight_interval: [],
				weight_unit_price: [],
				volume_interval: [],
				volume_unit_price: [],
				unit_price: {
					unit_price0: "0.0000",
					unit_price1: "0.0000",
					unit_price2: "0.0000",
					unit_price3: "0.0000",
					unit_price4: "0.0000",
					unit_price5: "0.0000",
					unit_price6: "0.0000",
					unit_price7: "0.0000",
					unit_price8: "0.0000",
					unit_price9: "0.0000",
					unit_price10: "0.0000",
					unit_price11: "0.0000",
					unit_price12: "0.0000",
					unit_price13: "0.0000",
					unit_price14: "0.0000",
					unit_price15: "0.0000"
				}
			},
		}
	},
	onLoad(option) {
		var obj;
		if (option.obj) {
			obj = JSON.parse(decodeURIComponent(option.obj));
			// obj = JSON.parse(option.obj)
		}
		this.page_type = obj.type;
		if (this.page_type == 'line') {
			var line = obj.line;
			this.inputData.company_id = line.logistics_id;
			this.inputData.company_name = line.logistics_name;
			this.inputData.deliver_point = line.receipt_site_ids;
			this.inputData.deliver_point_name = line.receipt_site_name;
			this.inputData.arrival_point = line.unload_site_ids;
			this.inputData.arrival_point_name = line.unload_site_name;
		} else if (this.page_type == 'logistics') {
			var logistics = obj.logistics;
			this.inputData.company_id = logistics.logistics_id;
			this.inputData.company_name = logistics.logistics_name;
		} else {}
		
		this.memberinfo = uni.getStorageSync(this.preutils.userinfo)
		this.inputData.deliver_point = this.memberinfo.site_id;
		this.inputData.deliver_point_name = this.memberinfo.site_name;
		this.getWayBillSn();
		this.getLogisticsService();
		this.getSiteInfo();
		this.getCompany();
	},
	onShow() {
		if (!this.check.isLogin()) {
			uni.navigateTo({
				url: "/pages/login/login/login"
			});
		}
		var pages = getCurrentPages(); // 获取当前页面栈
		var currentPage = pages[pages.length - 1]; // 当前页面
		this.refreshMethod(currentPage.data);
	
	},
	watch: {
		//haveTask 为接收参数的名称
		// inputData: {
		//   handler(newValue,oldValue) {
		//     this.circulation();//监听到数据变化执行方法
		//   },
		//   deep: true // 深度监听父组件传过来对象变化
		// },
		"inputData.delivery_fee": function(newval, oldval) {
			if (Number(newval) > 0) {
				this.inputData.delivery_type = "2";
			} else {
				this.inputData.delivery_type = "1";
			}
		},
		"inputData.order_amount_pay": function(newval, oldval) {
			this.inputData.delivery_fee_pay = newval;
			this.inputData.pickup_fee_pay = newval;
			this.inputData.transit_fee_pay = newval;
			this.receiptWatch(newval);
		},
		"inputData.order_amount": function(newval, oldval) {
			this.receiptWatch(newval);
		},

	},
	computed: {
		//开单费
		referenceCreateMoney() {
			let money = sysFreightTool.sysOpenOrderFreights(
				this.inputData,
				this.servicePriceData
			);
			this.inputData.open_order_fee = money;
			return money;
		},
		//系统使用费
		referenceSysMoney() {
			let money = sysFreightTool.sysOperateFreights(
				this.inputData,
				this.servicePriceData
			);
			this.inputData.operating_fee = money;
			return money;
		},
		//参考运费 - new - 20230914
		referenceFreightNew: function() {
			var refFreight = refeFreightTool.getRefAllFreights(this.inputData, this.searchPriceData);
			this.inputData.system_line_price = refFreight.system_line_price;
			this.inputData.system_markup_price = refFreight.system_markup_price;
			return refFreight.system_line_price;
		},
		referenceFreightStatus: function() {
			var refFreight = refeFreightTool.getRefAllFreights(this.inputData, this.searchPriceData);
			if (refFreight.system_line_price == 0 && !this.check.isNull(this.inputData.to_county_id)) {
				return true;
			}
			return false;
		},
		all_order_amount: function() {
			this.inputData.all_order_amount =tool.all_order_amount(this.inputData);
			return this.inputData.all_order_amount;
		}, //总费用（总运费）
		carry_order_amount: function() {
			this.inputData.carry_order_amount = tool.carry_order_amount(this.inputData);
			return this.inputData.carry_order_amount;
		}, //提付合计
		now_order_amount: function() {
			this.inputData.now_order_amount = tool.now_order_amount(this.inputData);
			return this.inputData.now_order_amount;
		}, //现付合计
		get_advance_amount: function() {
			return tool.get_advance_amount(this.inputData);
		},  
	},
	methods: {

		getWayBillSn() {
			// this.http.sendRequest({
			// 	api: this.api.order.setWaybillSn,
			// 	data: {},
			// 	success: res => {
			// 		console.log(res)
			// 		if (res.code == 1) {
			// 			this.inputData.waybill_sn = res.data.sn
			// 			this.inputData.goodsn = tool.getWaybillGoodSn(this.inputData);
			// 		}
			// 	},
			// 	fail: res => {
			// 		console.log('fail', res)
			// 	}
			// });
			this.inputData.waybill_sn = "T12023101000006";
			this.inputData.goodsn = tool.getWaybillGoodSn(this.inputData);
		},
		packPickerChange(e, r) {
			tool.packPickerChange(e, r, this.goodsPackList, this.inputData);
		},

		payPickerChange(e) {
			tool.payPickerChange(e, this.payFromList, this.inputData);
		},

		deliveryPickerChange(e) {
			tool.deliveryPickerChange(e, this.deliveryType, this.inputData);
		},

		receiptPickerChange(e) {
			tool.receiptPickerChange(e, this.receiptList, this.inputData);
		},
		switchReceiptChange(e) {
			tool.switchReceiptChange(e.detail.value, this.inputData);
		},
		receiptWatch(val) {
			tool.receiptWatch(val, this.inputData);
		},
		switchUnusualChange(e) {
			tool.switchUnusualChange(e, this.inputData);
		},
		switchUrgencyChange(e) {
			tool.switchUrgencyChange(e, this.inputData);
		},

		// 获取平台公司服务费配置
		getLogisticsService() {
			var data = {
				logistics_id: this.memberinfo.logistics_id,
			};
			this.http.sendRequest({
				api: this.api.order.logisticsServiceCharge,
				data: data,
				success: res => {
					if (res.code == "1") {
						this.servicePriceData = res.data;
						// localStorage.setItem(
						//   this.preutils.serviceCharge,
						//   JSON.stringify(res.data)
						// );
					}
				},
				fail: res => {
					console.log('fail', res)
				}
			});
		},

		// 获取价格基础数据 0、获取县级价格 1、获取市级价格
		getLogisticsPriceList(type) {
			var data = {
				to_province_id: this.inputData.to_province_id,
				to_city_id: this.inputData.to_city_id,
				to_county_id: this.inputData.to_county_id,
				logistics_id: this.memberinfo.logistics_id,
			};
			if (type == 1) {
				data.to_county_id = 0;
			}
			this.http.sendRequest({
				api: this.api.order.logisticsPriceSearchs,
				data: data,
				success: res => {
					if (res.code == "1") {
						console.log(res.code)
						this.searchPriceData = res.data;
						if (type == 0) {
							this.checkSearchPrice();
						}
					}
				},
				fail: res => {
					console.log('fail', res)
				}
			});
		},
		checkSearchPrice() {
			if (
				this.searchPriceData.weight_unit_price[0] ||
				this.searchPriceData.volume_unit_price[0]
			) {
				let wprice = this.searchPriceData.weight_unit_price[0];
				let vprice = this.searchPriceData.volume_unit_price[0];
				if (Number(wprice) <= 0 || Number(vprice) <= 0) {
					this.getLogisticsPriceList(1);
				}
			} else {
				this.getLogisticsPriceList(1);
			}
		},
		getCompany() {
			var data = {
				page: 1,
				page_size: 9999
			}
			this.http.sendRequest({
				api: this.api.home.logisticsListApi,
				data: data,
				success: res => {
					if (res.code == 1) {
						this.companyList = res.data.data
					}
				},
				fail: res => {
					console.log('fail', res)
				}
			});
		},
		getStartSite() {
			var data = {
				page: 1,
				page_size: 9999,
				logistics_id: this.inputData.company_id
			}
			this.http.sendRequest({
				api: this.api.home.logisticsSiteListApi,
				data: data,
				success: res => {
					if (res.code == 1) {
						this.startSiteList = res.data.data
					}
				},
				fail: res => {
					console.log('fail', res)
				}
			});
		},
		getEndSite() {
			var data = {
				page: 1,
				page_size: 9999,
				logistics_id: this.inputData.company_id
			}
			this.http.sendRequest({
				api: this.api.home.logisticsSiteListApi,
				data: data,
				success: res => {
					if (res.code == 1) {
						this.endSiteList = res.data.data
					}
				},
				fail: res => {
					console.log('fail', res)
				}
			});
		},
		getSiteInfo() {
			this.http.sendRequest({
				api: this.api.order.sSiteInfoApi,
				data: {
					site_id: 1
				},
				success: res => {
					if (res.code == 1) {
						this.siteInfo = res.data
					}
				},
				fail: res => {
					console.log('fail', res)
				}
			});
		},


		bindPickerChange(e) {
			this.address_type_city = e;
			this.$refs.popup.open();
			uni.hideTabBar();
			this.getRegion(0, 1)
		},
		getRegion(pid, type) {
			this.http.sendRequest({
				api: this.api.order.sProvinceListApi,
				data: {
					pid: pid
				},
				success: res => {
					console.log(res, '===province')

					if (type == 1) {
						this.provinceList = res.data

						//第一次进来时，获取第二列数据
						if (pid == 0) {
							this.getRegion(this.provinceList[0].id, 2)
						}

					} else if (type == 2) {
						this.cityList = res.data
						//默认获取市 下面的区，并且没滚动的时候 设置第二和第三列的index为0
						this.getRegion(this.cityList[0].id, 3)
						this.selectList[1] = 0;
						this.selectList[2] = 0;
					} else {
						this.areaList = res.data
					}

				},
				fail: res => {
					console.log('fail', res)
				}
			});
		},

		selectData(e, type) {
			console.log(e, '====e', )
			let val = e.detail.value;
			if (this.selectList[0] !== val[0]) {
				this.getRegion(this.provinceList[val[0]].id, 2)
				this.cityList = []
				this.areaList = [];
			} else if (this.selectList[1] !== val[1]) {
				this.getRegion(this.cityList[val[1]].id, 3)
				this.areaList = [];
			}
			this.selectList = val;
		},
		confirm(e) {
			let proItem = this.provinceList[this.selectList[0]]
			let cityItem = this.cityList[this.selectList[1]]
			let areaItem = this.areaList[this.selectList[2]]
			console.log(this.selectList[0], this.provinceList[this.selectList[0]], '====')
			if (this.address_type_city == 1) {
				this.inputData.take_city = proItem.name + ' ' + cityItem.name + ' ' + areaItem.name
				this.inputData.take_province_id = proItem.id
				this.inputData.take_city_id = cityItem.id
				this.inputData.take_area_id = areaItem.id
			} else if (this.address_type_city == 2) {
				this.inputData.to_address = proItem.name + ' ' + cityItem.name + ' ' + areaItem.name
				this.inputData.to_province_id = proItem.id
				this.inputData.to_city_id = cityItem.id
				this.inputData.to_county_id = areaItem.id
				this.getLogisticsPriceList(0);
			} else {
				this.inputData.send_city = proItem.name + ' ' + cityItem.name + ' ' + areaItem.name
				this.inputData.send_province_id = proItem.id
				this.inputData.send_city_id = cityItem.id
				this.inputData.send_area_id = areaItem.id
			}

			this.$refs.popup.close()
			uni.showTabBar();
		},
		close() {
			this.$refs.popup.close()
			uni.showTabBar();
		},

		refreshMethod(e) {
			if(e){
				if (e.inputData.addressType == '1') {
					if (!this.check.isNull(e.fromData, 'obj')) {
						this.inputData.fromData = e.fromData;
					}
				} else {
					if (!this.check.isNull(e.toData, 'obj')) {
						this.inputData.toData = e.toData;
					}
				}
				
				if (!this.check.isNull(this.inputData.toData, 'obj') && !this.check.isNull(this.inputData.fromData,
						'obj')) {
					this.orderLogisticsData();
				}
				if (this.check.isNull(e.inputData.addressType)) {
				
				}
			}
			
		},
		fromClick() {
			this.$util.redirectTo('/pages/mine/address/address', {
				addressType: '1',
				backType: '1'
			});
		},
		toClick() {
			this.$util.redirectTo('/pages/mine/address/address', {
				addressType: '2',
				backType: '1'
			});
		},
		goodsTypePickerChange(e) {
			var goodsItem = this.goodsTypeList[e.detail.value];
			this.inputData.goodsType = goodsItem.label;
			this.inputData.goodsTypeId = goodsItem.code;
		},
		companyPickerChange(e) {
			var companyItem = this.companyList[e.detail.value];
			this.inputData.company_name = companyItem.logistics_name;
			this.inputData.company_id = companyItem.logistics_id;
			this.getStartSite();
			this.getEndSite();
		},

		goDetail(e) {
			console.log(e)
			this.$util.redirectTo('/pages/home/search/company-detail/company-detail', {
				logistics_id: e.id
			});
		},
		addGoodClick() {
			var goods = {
				goods_name: '',
				goods_pack: '',
				goods_num: '',
				total_weight: '',
				total_volume: '',
			}
			this.inputData.goods.push(goods);
		},
		subGoodsClick(index) {
			if (this.inputData.goods.length == 1) {
				this.inputData.goods.splice(index, 1);
				var goods = {
					goods_name: '',
					goods_pack: '',
					goods_num: '',
					total_weight: '',
					total_volume: '',
				}
				this.inputData.goods.push(goods);
			} else {
				this.inputData.goods.splice(index, 1);
			}

		},
		validCheckData() {
			const that = this;
			if (!this.check.phone_check('发货人', this.inputData.send_mobile)) {
				return false;
			}
			if (!this.check.phone_check('收货人', this.inputData.take_mobile)) {
				return false;
			}
			if (!this.check.check_amount('运费', this.inputData.order_amount)) {
				return false;
			}
			if (!this.check.isNull(this.inputData.delivery_fee)) {
				if (!this.check.check_amount('送货费', this.inputData.delivery_fee)) {
					return false;
				}
			}
			if (!this.check.isNull(this.inputData.pickup_fee)) {
				if (!this.check.check_amount('接货费', this.inputData.pickup_fee)) {
					return false;
				}
			}
			if (!this.check.isNull(this.inputData.advance_amount)) {
				if (!this.check.check_amount('代收货款', this.inputData.advance_amount)) {
					return false;
				}
			}

			if (this.check.isNull(this.inputData.to_county_id)) {
				this.$util.showToastErr('请选择目的城市')
				return false;
			}
			if (this.check.isNull(this.inputData.system_line_price)) {
				this.$util.showToastErr('暂无此地区专线运费，请联系客服:15092939826')
				return false;
			}
			if (this.inputData.goods.length <= 0) {
				this.$util.showToastErr('请添加货物')
				return false;
			} else {
				var flag = false;
				this.inputData.goods.forEach((item) => {
					if (!item.goods_name || !item.goods_pack || !item.goods_nums) {
						flag = true;
					}
				});
				if (flag) {
					this.$util.showToastErr("货物信息不能为空");
					return false;
				}
			}
			return true;
		},

		submitClick() {
			if (this.validCheckData()) {
				uni.showModal({
					title: '提示',
					content: '是否提交数据，创建运单！',
					cancelText: '取消',
					confirmText: '确定',
					success: (res) => {
						if (res.confirm) {
							this.addOrderData();
						}
					}
				})
			}
		},
		handleParamsData() {
			console.log(this.inputData)
			this.inputData.line_id = this.memberinfo.line_id;
			this.inputData.company_id = this.memberinfo.logistics_id;
			// this.inputData.deliver_point
			console.log(this.memberinfo)
			tool.handleParamsData(this.inputData);
			console.log(this.inputData)
			
		},
		// 	POST一键下单
		addOrderData() {
			this.handleParamsData();
			
			let data = {
				...this.inputData,
				openid: uni.getStorageSync('openid')
			}
			this.$refs.loadingCover.show();
			this.http.sendRequest({
				api: this.api.order.waybillCreate,
				data: data,
				success: res => {
					console.log(res)
					if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
					if (res.code == 1 && res.data) {
						this.inputData = utils.getInitInputDataData(),
						uni.showModal({
							title: '开单成功',
							success: (res) => {

							}
						})
					}
				},
				fail: res => {
					uni.showToast({
						title: res.data
					})
					if (this.$refs.loadingCover) this.$refs.loadingCover.hide();
				}
			});
		},


		// 根据收发货地获取物流公司
		orderLogisticsData() {
			var data = {
				from_id: this.inputData.fromData.address_id,
				to_id: this.inputData.toData.address_id,
			};
			this.http.sendRequest({
				api: this.api.order.sOrderLogisticsApi,
				data: data,
				success: res => {
					console.log(res)
					if (res.success == 'true' && res.data) {
						this.companyList = res.data
					}
				}
			});
		},

		/**
		 * 商家个人信息
		 */
		mineShipperInfoData() {
			this.http.sendRequest({
				api: this.api.mine.mineShipperInfoApi,
				data: {},
				success: res => {
					console.log(res)
					if (res.success == 'true' && res.data) {

						getApp().globalData.userInfo = res.data;
					}
				}
			});
		},


	}

}